﻿// JSONData.ts
import { Singleton } from "../utils/Singleton";
import { EquipInfo } from "./JSONDataInterface"; // 导入接口
import { ConfigType, JSONManager } from "./JSONManager";

class ConfigAccessor<T> {
  private configMap: Map<number, T> = new Map();
  constructor(private configName: ConfigType, private keyField: string) {}

  public async load(): Promise<void> {
    const jsonManager = JSONManager.getInstance();
    const rawConfig = await jsonManager.loadConfigAsync<{ [key: string]: any }>(
      this.configName
    );

    if (rawConfig) {
      for (const key in rawConfig) {
        const item = rawConfig[key];
        const id = item[this.keyField];
        this.configMap.set(id, item);
      }
    }
  }

  public get(id: number): T | undefined {
    return this.configMap.get(id) as T;
  }

  public getAll(): Map<number, T> {
    return this.configMap;
  }
}

export class JSONDataClass extends Singleton<JSONDataClass> {
  private loaded = false;
  private constructor() {
    super();
  }

  // 配置类 根据需求自行拓展
  public readonly equip = new ConfigAccessor<EquipInfo>("equipCfg", "id");

  public async ensureLoaded() {
    if (!this.loaded) {
      await Promise.all([this.equip.load()]); //这里对应做扩充
      this.loaded = true;
    }
  }
}
